package com.umpay.utils;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.umpay.exception.BusinessException;

public class JAXBUtil {
	
	private static final Logger logger = LogManager.getLogger(JAXBUtil.class);

	public static <V> Object initJAXB(String message, Class<V> clazz) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			StringReader reader = new StringReader(message);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			SAXParserFactory sax = SAXParserFactory.newInstance();
			sax.setNamespaceAware(false);
			XMLReader xmlReader = sax.newSAXParser().getXMLReader();
			Source source = new SAXSource(xmlReader, new InputSource(reader));
			Object obj = unmarshaller.unmarshal(source);
			return obj;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			BusinessException bizException = new BusinessException("70001", "解析失败,核对参数！");
			throw bizException;
		}
	}

}
